import React, {Component} from 'react'
import {FlatList, View} from "react-native";
import Item from "../item/Item";

export default class Recommendation extends Component {

    todayUrl = "http://192.168.31.125:9091/api/item/coupons/page";
    tpwdUrl = "http://192.168.31.125:9091/api/tpwd/create";

    constructor() {
        super();
        this.state = {
            currentPage: 1,
            loading: false,
            itemList: [],
        };
        this.init()

    }

    init = () => {
        fetch(this.todayUrl + "?pageNo=" + this.state.currentPage, {
            method: "GET"
        }).then((response) => response.json()).then((response) => {
            console.log(response);
            if (response.results) {
                let newList = [].concat(this.state.itemList).concat(response.results);
                console.log("加载第" + this.state.currentPage + "页数据", newList);
                this.setState({itemList: newList, loading: false, currentPage: this.state.currentPage + 1});
            }
        }).catch((err) => {
            console.log("网络异常" + JSON.stringify(err));
        });
    };
    render() {
        return (
            <View style={{flex: 1}}>
                <FlatList
                    // horizontal={true}
                    numColumns={2}
                    data={this.state.itemList}
                    renderItem={({item}) =>

                        <Item itemData={item}/>

                    }
                    initialNumToRender={12}
                    onEndReachedThreshold={0.1}
                    onEndReached={(info) => this.getMoreItem()}
                />
            </View>
        )
    }


    getMoreItem = () => {
        if (this.state.loading) {
            return
        }
        let page = this.state.currentPage + 1;
        fetch(this.todayUrl + "?q=旗舰店&pageNo=" + page, {
            method: "GET"
        }).then((response) => response.json()).then((response) => {
            console.log(response);
            if (response.results) {
                let newList = [].concat(this.state.itemList).concat(response.results);
                console.log("加载第" + page + "页数据", newList);
                this.setState({itemList: newList, loading: false, currentPage: page});
            }
        }).catch((err) => {
            console.log("网络异常" + JSON.stringify(err));
        });
    }
}